package com.qy.controller.manage;

import com.qy.base.core.*;
import com.qy.base.utils.DateUtil;
import com.qy.base.utils.MyMD5;
import com.qy.model.*;
import com.qy.service.AdminService;
import com.github.pagehelper.PageHelper;
import com.qy.service.PermissionsService;
import com.qy.service.RolePermissionsService;
import com.qy.service.RolesService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by zaq on 2018/06/21.
 */
@RestController
@RequestMapping("/manage/admin")
public class AdminController {
    @Resource
    private AdminService adminService;

    @Resource
    private RolesService rolesService;

    @Resource
    private RolePermissionsService rolePermissionsService;

    @Resource
    private PermissionsService permissionsService;

    //登录login
    @PostMapping("/login")
    public Result login(@RequestBody Admin admin) {
        if (admin.getAccount() == null || admin.getAccount().isEmpty()) {
            throw new ServiceException(Constants.CODE_ERR_USER_NAME);
        }
        if (admin.getPassword() == null || admin.getPassword().isEmpty()) {
            throw new ServiceException(Constants.CODE_ERR_USER_NAME);
        }
        Condition condition = new Condition(Admin.class);
        Example.Criteria criteria = condition.createCriteria();
        criteria.andCondition("account = '" + admin.getAccount() + "'");
        List<Admin> adminList = adminService.findByCondition(condition);
        if (adminList.size() == 0) {
            throw new ServiceException(Constants.CODE_ERR_ACCOUNT_NO_EXIST);
        }
        Admin admin1 = adminList.get(0);
        String password = MyMD5.myMD5(admin.getPassword());
        if (!password.equals(admin1.getPassword())) {
            throw new ServiceException(Constants.CODE_ERR_PASSWORD_ERR);
        }
        List<Permissions> list = adminService.permissionsList(admin1.getRole_id());
        Integer role_id = admin1.getRole_id();
        for (Permissions permissions : list) {
            Integer id = permissions.getId();
            List<Permissions> p = permissionsService.selectSubPermissionsList(id, role_id);

            permissions.setSub_permissions((ArrayList) p);
        }
        return ResultGenerator.successResult(admin1, list);
    }

    //增加用户
    @PostMapping("/add")
    public Result add(@RequestBody Admin admin) {
        if (admin.getAccount() == null || admin.getAccount().isEmpty()) {
            throw new ServiceException(Constants.CODE_ERR_USER_NAME);
        }
        if (admin.getPassword() == null || admin.getPassword().isEmpty()) {
            throw new ServiceException(Constants.CODE_ERR_USER_NAME);
        }
        String username = admin.getAccount();
        String password = MyMD5.myMD5(admin.getPassword());
        if (username == null || password == null) {
            throw new ServiceException(Constants.CODE_ERR_USER_NAME);
        } else {

            Condition condition = new Condition(Admin.class);
            Example.Criteria criteria = condition.createCriteria();
            criteria.andCondition("account = '" + admin.getAccount() + "'");
            List<Admin> adminList = adminService.findByCondition(condition);

            if (adminList.size() != 0) {
                throw new ServiceException(Constants.CODE_ERR_ACCOUNT_EXIST);
            }
        }
        if (admin.getReal_name() != null && !admin.getReal_name().isEmpty()) {
            Condition condition = new Condition(Admin.class);
            Example.Criteria criteria = condition.createCriteria();
            criteria.andCondition("real_name = '" + admin.getReal_name() + "'");
            List<Admin> adminList = adminService.findByCondition(condition);

            if (adminList.size() != 0) {
                throw new ServiceException(Constants.CODE_ERR_REAL_NAME_EXIST);
            }
        }

        admin.setPassword(password);
        admin.setAdd_time(DateUtil.getNowTimestamp());
        adminService.save(admin);
        return ResultGenerator.successResult();
    }

    //删除用户
    @PostMapping("/delete")
    public Result delete(@RequestBody Admin admin) {
        adminService.deleteById(admin.getId());
        return ResultGenerator.successResult();
    }

    //修改密码
    @GetMapping("/changePassword")
    public Result changePassword(Integer id, String oldPassword, String newPassword) {
        Admin admin = adminService.findById(id);
        if (admin == null) {
            return ResultGenerator.errResult(Constants.CODE_ERR_ACCOUNT_NO_EXIST);
        }
        if (MyMD5.myMD5(oldPassword).equals(admin.getPassword())) {
            if (MyMD5.myMD5(newPassword).equals(admin.getPassword())) {
                throw new ServiceException(Constants.CODE_ERR_NEW_PASSWORD_ERR);
            }
            admin.setPassword(MyMD5.myMD5(newPassword));
            adminService.update(admin);
            return ResultGenerator.successResult();
        } else {
            return ResultGenerator.errResult(Constants.CODE_ERR_OLD_PASSWORD_ERR);
        }
    }

    //更新
    @PostMapping("/update")
    public Result update(@RequestBody Admin admin) {
        Condition condition = new Condition(Member.class);
        Example.Criteria criteria = condition.createCriteria();
        criteria.andCondition("account = '" + admin.getAccount() + "'");
        List<Admin> adminList = adminService.findByCondition(condition);
        Admin admin1 = adminList.get(0);
        admin1.setReal_name(admin.getReal_name());
        admin1.setRole_id(admin.getRole_id());
        adminService.update(admin1);
        return ResultGenerator.successResult();
    }

    //重置密码
    @GetMapping("/reset")
    public Result reset(Admin admin) {
        Admin admin1 = adminService.findById(admin.getId());
        if (admin1 != null) {
            admin1.setPassword(MyMD5.myMD5(admin.getPassword()));
            adminService.update(admin1);
        }
        return ResultGenerator.successResult();
    }

    //人员列表
    @GetMapping("/list")
    public Result list(Admin admin, PageBean<Map> page) {
        PageHelper.startPage(page.getPageNum(), page.getSize(), "add_time desc");
        List<Map> list = adminService.selectAdminList(admin);
        page.setList(list);
        return ResultGenerator.successResult(page);
    }

    //详情
    @GetMapping("/detail")
    public Result detail(Integer id) {
        Admin admin = adminService.findById(id);
        return ResultGenerator.successResult(admin);
    }

    //角色权限列表
    @GetMapping("/permissionsList")
    public Result permissionsList(Admin admin) {
        if (admin.getRole_id() != null) {
            List<Permissions> list = adminService.permissionsList(admin.getRole_id());
            Integer role_id = admin.getRole_id();
            for (Permissions permissions : list) {
                Integer id = permissions.getId();
                List<Permissions> p = permissionsService.selectSubPermissionsList(id, role_id);

                permissions.setSub_permissions((ArrayList) p);
            }
            return ResultGenerator.successResult(list);
        } else {
            return ResultGenerator.successResult(permissionsService.findAll());
        }
    }

    //设置角色权限
    @PostMapping("/configPermission")
    public Result configPermission(@RequestBody Admin admin) {
        if (admin.getRole_id() != null && admin.getPermissionsList() != null) {
            Integer role_id = admin.getRole_id();
            Roles roles = rolesService.findById(admin.getRole_id());
            if (roles == null) {
                return ResultGenerator.errResult(Constants.CODE_NOT_EXIST_ROLES);
            }
            List<RolePermissions> rolePermissionsList = new ArrayList<>();
            rolePermissionsService.deleteByCSql("role_id = " + admin.getRole_id());
            if (!admin.getPermissionsList().isEmpty()) {
                for (Integer id : admin.getPermissionsList()) {
                    Permissions permissions = permissionsService.findById(id);
                    RolePermissions rolePermissions = new RolePermissions();
                    if (permissions.getPid() != null && rolePermissionsService.selectRolePermissions(id, role_id).size() == 0) {
                        rolePermissions.setRole_id(admin.getRole_id());
                        rolePermissions.setPermission_id(permissions.getPid());
                        rolePermissionsList.add(rolePermissions);
                    }
                    rolePermissions.setRole_id(admin.getRole_id());
                    rolePermissions.setPermission_id(id);
                    rolePermissionsList.add(rolePermissions);
                }
                rolePermissionsService.save(rolePermissionsList);
            }
            //更新后查询该角色下的权限并返回
            List<Permissions> list = adminService.permissionsList(admin.getRole_id());
            for (Permissions permissions : list) {
                Integer id = permissions.getId();
                List<Permissions> p = permissionsService.selectSubPermissionsList(id, role_id);

                permissions.setSub_permissions((ArrayList) p);
            }
            return ResultGenerator.successResult(list);

        } else {
            return ResultGenerator.errResult(101);
        }
    }

}
